<script lang="ts" setup>
import { ref, reactive, onMounted, shallowRef, watch, toRaw, nextTick } from 'vue'
import {
  NSpace,
  NButton,
  type FormInst,
  useMessage,
  NScrollbar,
  NSpin,
  type DataTableColumns,
  NImageGroup,
  NImage,
  NTooltip
} from 'naive-ui'
import VUpload from '@/views/OA/Common/Upload.vue'
import { sendRequest } from '@/utils/api'
import FixedAction from '@/components/FixedAction.vue'
import { keysOf } from '@/utils/object'
import { useRoute } from 'vue-router'
import { mergeWith, isArray } from 'lodash-es'
import DynamicPageForm from '@/components/DynamicPageForm/DynamicPageForm.vue'
import type { ModelJson } from '@/components/DynamicPageForm/DynamicFormTypes'
import basicInfo from '@/components/CollectProcess/BasicInfo.vue'
import InfoBatch from '@/components/CollectProcess/InfoBatch/index.vue'
import InfoGoods from '@/components/CollectProcess/InfoGoods/index.vue'
import VAttachments from '@/views/CollectionManagement/CollectionProcess/CollectingItems/Attachments.vue'
import useSubmit,{defaultVersionTypeValue,defaultVersionTypeKey} from '@/components/DynamicFormComponent/useSubmit'
import DynamicFormComponent from '@/components/DynamicFormComponent/index.vue'
import useRouteQuery from '@/hooks/useRouteQuery'
import useRouteReplace from '@/hooks/useRouteReplace'
const { dfInst, formData, createVars,submitLoading,submit:submitR } = useSubmit()
const props = defineProps({
  id: { type: String, default: () => null },
  idSelf: { type: String, default: () => null },
  typeShow: { type: String, default: () => '1' },
  code: { type: String, default: () => null },
  batchCode: { type: String, default: () => null },
  subItemCode: { type: String, default: () => null }
})
const route=useRoute()
const routeReplace = useRouteReplace(route.query.redirect as string)

const tableData1 = ref()
const idRef=props.id
const array = props?.id?.split(',') || []
const fileImgList: any = ref([]) //附件数组
const form: any = reactive({
  id: array?.[0],
  password: array?.[0] ? null : 'Aa123456!',
  userStatus: 1,
  typeTree: null,
  typeTreeS: null,
  typeTreeT: null,
  time: null,
  name: null,
  repactName: null,
  collectName: null,
  phone: null,
  person: null,
  dujiaoName: null,
  Uptime: null,
  price: null,
  author: null,
  number1: null,
  yesNO: null,
  yinciTime: null,
  remack: null,
  ziicaCode: null,
  serialNumber: null,
  position: null,
  itemsStaging: {
    assetCode: null,
    firstLevelCode: null,
    threeLevelCode: null,
    secondLevelCode: null,
    fifthLevelCode: null,
    fourthLevelCode: null,
    serialNumber: null
  }
})
const oneSelectValue = ref<string | null>(null)
const oneSelectOptions = shallowRef<[]>([])
const oneSelectLoading = ref(false)

const twoSelectValue = ref<string | null>(null)
const twoSelectOptions = shallowRef<[]>([])
const twoSelectLoading = ref(false)

const threeSelectValue = ref<string | null>(null)
const threeSelectOptions = shallowRef<[]>([])
const threeSelectLoading = ref(false)

const isUseLastSelect = ref(true)
const clueMethodOptions: any = reactive([])
const formInst = ref<FormInst | null>(null)
// const formData = ref({} as any)

const validatorTypeFormItem = () => {
  if (isUseLastSelect.value) return threeSelectValue.value !== null
  return twoSelectValue.value !== null
}
const modelJson = ref({} as ModelJson)
const queryJsonBM = async (code: string) => {
  try {
    const [error, res]: any = await sendRequest({
      module: 'collection',
      api: 'jsonContent',
      override: {
        params: {
          name: `BM_${code}.json`
        }
      }
    })
    if (error) throw error
    if (res.code !== 200) throw new Error(res.message)
    otherJson.value = res.data
  } catch (error) {
    console.error(error)
  }
}
const queryJson = async (code: string) => {
  try {
    const [error, res]: any = await sendRequest({
      module: 'collection',
      api: 'jsonContent',
      override: {
        params: {
          name: `${code}.json`
        }
      }
    })
    if (error) throw error
    if (res.code !== 200) throw new Error(res.message)
    modelJson.value = res.data
    return res.data
  } catch (error) {
    console.error(error)
  }
}
const baseModel: ModelJson = {
  elements: [
    {
      type: 'NInput',
      key: 'itemName',
      label: '名称：',
      rule: {
        required: true,
        message: '名称必填'
      }
    },
    {
      type: 'NDatePicker',
      key: 'receiveTime',
      label: '接收时间：',
      props: { type: 'datetime', format: 'yyyy-MM-dd HH:mm:ss' },
      style: { flex: 1 },
      rule: {
        required: true,
        message: '接收时间必填'
      }
    },
    {
      type: 'NSelect',
      key: 'collectTypeName',
      label: '征集方式：',
      props: {
        options: clueMethodOptions,
        valueField: 'code',
        labelField: 'name'
      },
      rule: {
        required: true,
        message: '征集方式必填'
      }
    },
    {
      type: 'NInputNumber',
      key: 'itemNum',
      label: '数量：',
      style: { flex: 1 },
      props: {
        showButton: false,
        min: 0
      },
      rule: {
        type: 'number',
        required: true,
        message: '数量必填'
      }
    },
    {
      type: 'NInput',
      key: 'receiveUser',
      label: '接收人：',
      rule: {
        required: true,
        message: '接收人必填'
      }
    },
    {
      type: 'NInput',
      key: 'notes',
      label: '备注：',
      props: {
        type: 'textarea',
        rows: 1
      },
      rule: {
        required: true,
        message: '备注必填'
      }
    }
  ]
}
// const model = shallowRef<any>(baseModel)
// const setModelJson = async (code?: string | null) => {
//   if (!code) return (model.value = toRaw(baseModel))
//   model.value = mergeWith({}, toRaw(baseModel), await queryJson(code), (obj: any, src: any) => {
//     if (isArray(obj)) return [...obj, ...src]
//   }) as ModelJson
// }
const clueInfoLoading = ref(false)
const checkIsDetail = async (code: any) => {
  try {
    const [error, res] = await sendRequest({
      module: 'collectProcess',
      api: 'info',
      uri: {
        itemCode: code as string
      }
    })
    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)

    // await setModelJson(res.data.itemTypeCode)
    const { data } = res
    // formData.value = Object.assign(
    //   {},
    //   {
    //     itemName: data.itemName,
    //     receiveTime: data.receiveTime,
    //     itemTypeCode: data.itemTypeCode,
    //     itemTypeName: data.itemTypeName,
    //     itemNum: data.itemNum,
    //     collectTypeName: data.collectTypeName,
    //     receiveUser: data.receiveUser,
    //     notes: data.notes,
    //     itemTypeItem: data.itemTypeName
    //   },
    //   JSON.parse(data.jsonStr || '{}')
    // )
    // fileList.value = data.fileList?.map((e: any, i: number) => ({
    //   id: i,
    //   name: e.name,
    //   status: 'finished',
    //   url: e.path,
    //   remoteId: e.id
    // }))
  } catch (error) {
    console.error(error)
  } finally {
    setTimeout(() => {
      clueInfoLoading.value = false
    }, 2000)
  }
}
// 返回
const goBack = () => {
  // history.back()
  routeReplace()
}
const otherJson = ref({} as ModelJson)

// const queryTypeJson = async (type: string): Promise<any> => {
//   return await (await fetch(`/form-models/${type}.json`)).json()
// }
// watch(
//   () => formData.value.type,
//   async (type) => {
//     if (!type) return (model.value = baseModel)
//     model.value = mergeWith({}, baseModel, await queryTypeJson(type), (obj: any, src: any) => {
//       if (isArray(obj)) return [...obj, ...src]
//     })
//   },
//   { immediate: true }
// )
const getJSONInfo = async (subItemCode: any) => {
  sendRequest({
    module: 'collectProcess',
    api: 'commonJsonInfo',
    uri: {
      subItemCode: subItemCode
    }
  }).then(async ([err, res]) => {
    if (err) return
    formData.value =JSON.parse(res.data?.catalogInfo||`{"${defaultVersionTypeKey}": "${defaultVersionTypeValue}" }`)
    if (formData.value['BMCOM006']) formData.value['BMCOM006'] = formData.value['BMCOM006'].split('>').pop()
    if(formData.value?.['BMCOM003']?.indexOf('T002')!=-1)
  {
    if(formData.value.toString()!='{}')
     if (formData.value.ZRZ?.[0]?.['BMLSWX012'])
      formData.value['BMCOM008']= `${formData.value.ZRZ?.[0]?.['BMLSWX012'] || ''}${formData.value.ZRZ?.[0]?.['BMLSWX011'] ? '(' + formData.value.ZRZ?.[0]?.['BMLSWX011'] + ')' : ''}${formData.value.ZRZ?.[0]?.['BMLSWX013'] || ''}`
     
  }
    // res.data?.fileList?.map((i: any) => {
    //   fileImgList.value.push({
    //     name: i.name,
    //     url: i.path,
    //     status: 'finished',
    //     id: i.id
    //   })
    // })
  })
}
const getInfo = async () => {
  return sendRequest({
    module: 'collectProcess',
    api: 'catalogInfo',
    uri: {
      subItemCode: props.subItemCode
    }
  }).then(async ([err, res]) => {
    if (err) return

    keysOf(res.data.detailVo).forEach((e) => {
      form[e] = res.data[e] as never
    })
    console.log(res.data)
    res.data?.collectingItems?.fileList?.map((i: any) => {
      fileImgList.value.push({
        name: i.name,
        url: i.path,
        status: 'finished',
        id: i.id
      })
    })
    // queryJsonBM(res.data?.detailVo?.itemTypeCode)
    // checkIsDetail(res.data?.detailVo?.itemCode)
    // modelJson.value = JSON.parse(res.data?.detailVo?.jsonStr)
    getJSONInfo(props.subItemCode)
  })
}
const getFlowFn = () => {
  return sendRequest({
    module: 'collectProcess',
    api: 'orderBaseInfo',
    override: {
      params: {
        id: props?.code
      }
    }
  }).then(async ([err, res]) => {
    if (err) return
    // keysOf(res.data).forEach((e) => {
    //   form[e] = res.data[e] as never
    // })
    tableData1.value = res.data?.workflowInfoVo?.approvalRecordsList || []
  })
}

const showLoading = ref(false)

watch(
  () => route,
  async () => {
    if (route.path == '/collection/process/makeMenu/processDetailNew' && props.id) {
      showLoading.value = true
      fileImgList.value = []
      getInfo()
     
      showLoading.value = false
    }
  },
  {
    deep: true,
    immediate: true
  }
)
useRouteQuery('id', () => {
  if (route.query.id) getInfo()
})

// onMounted(async () => {
//   // 修改回显
//   if (props.id) {
//     getInfo()
//     getTimeLine()
//   }
// })
</script>

<template>
  <DetailFormProvider>
    <div class="main" :key="idRef">
      <div class="form_content">
        <NScrollbar>
          <NSpin :show="showLoading">
            <div class="topTitle">批次信息</div>
            <InfoBatch :key='props.batchCode' :id="props.batchCode" />
            <div class="topTitle"  v-if="props?.typeShow!='0'">物品信息</div>
            <InfoGoods
              :id="props.id"
              :key='props.id'
              :subItemCode="props.subItemCode"
              :code="props.idSelf"
              v-if="props?.typeShow!='0'"
            />
            <!-- 无需编目为false展示 -->
            <div v-if="props?.typeShow=='0'">
              <div class="dynamic-form-demo">
          <DynamicFormComponent ref="dfInst" v-if='formData.BMCOM003' :disabled="true" :data="formData" :createVars="createVars" />
        </div>
            <!-- <DynamicPageForm
              ref="formInst"
              :form-model="otherJson"
            
              :model="formData"
              :form-data="formData"
              label-placement="left"
              require-mark-placement="left"
              label-width="140rem"
              :disabled="true"
              @update:value="handleUpdateFormData"
            /> -->
            <div
              class="topTitle"
              v-show="fileImgList?.length > 0"
            >
              附件
            </div>
            <div
              class="detailinlineStyle"
            >
              <span
                v-show="fileImgList?.length > 0"
                style="margin-right: 10px"
              >
                附件:
              </span>
              <div>
                <n-image-group>
                  <n-space>
                    <n-image
                      width="100"
                      height="100"
                      :src="i.url"
                      :key="i.id"
                      v-for="i in fileImgList"
                    />
                  </n-space>
                </n-image-group>
              </div>
            </div>
          </div>
            <!-- <div>暂无附件</div> -->
          </NSpin>
        </NScrollbar>
      </div>
    </div>
  </DetailFormProvider>
  <FixedAction>
    <NSpace justify="center">
      <NButton
        style="width: 78px"
        ghost
        @click="goBack"
      >
        取消
      </NButton>
      <!-- <NButton type="primary" style="width: 78px" @click="submit" :loading="loading" v-if="props?.typeShow == 0">
        确定
      </NButton> -->
    </NSpace>
  </FixedAction>
</template>

<style>
.tooltip {
  position: relative;
}
.detailinlineStyle {
  display: flex;
  width: 100%;
  margin-bottom: 20px;
  margin-left: 45px;
}
.dynamic-form-demo {
    padding: 30px 45px 10px;
    background-color: #e1e1e1;
  }
.tooltip:hover::after {
  display: block;
}

.tooltip:hover::before {
  display: block;
}

.tooltip::after {
  content: attr(data-title);
  position: absolute;
  top: -37rem;
  left: 50%;
  transform: translateX(-50%);
  max-width: 300rem;
  padding: 5rem 10rem;
  background-color: #ffffff;
  color: #333333;
  border-radius: 5rem;
  font-size: 14rem;
  z-index: 999;
  display: none;
}

.tooltip::before {
  content: '';
  position: absolute;
  top: -7rem;
  left: 50%;
  transform: translateX(-50%);
  border: 5rem solid transparent;
  border-top-color: #ffffff;
  display: none;
}
</style>

<style scoped lang="scss">
@mixin CommonFont {
  font-size: 18rem;
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  color: #333333;
}

.main {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  overflow: hidden;
  padding: 0 0 110rem;

  .form_content {
    width: 100%;
    height: 100%;
    padding: 20rem 20rem 0;

    .topTitle {
      font-size: 22px;
      font-family: PingFangSC, PingFang SC;
      font-weight: 500;
      color: #5fb17f;
      margin-bottom: 10rem;
    }

    .inputWH {
      flex: 1;
    }

    .inputWHmin {
      width: 150rem;
    }

    .content {
      display: flex;
      flex-direction: column;
      width: 100%;
      height: 100%;
      padding: 18rem 33rem 120rem;
      overflow-y: scroll;
      background-color: #ebeceb;
      @include CommonFont;
    }

    .content1 {
      width: 400px;
      height: 100%;
      padding: 18rem 33rem 120rem;
      background-color: #ebeceb;
      @include CommonFont;

      :deep(.n-timeline-item-timeline__circle) {
        background-color: #008000;
        border: 1px solid #008000;
      }

      :deep(
          .n-timeline .n-timeline-item .n-timeline-item-content .n-timeline-item-content__content
        ) {
        transform: translate(0, -50%);
        // margin-top: 14px;
        position: relative;
      }

      .namePosition {
        position: absolute;
        left: -96rem;
        top: calc(50% - 11px);
      }
    }
  }

  .approve {
    display: flex;
    width: 100%;
    margin-bottom: 20rem;
    border-bottom: 1px dashed #bc9e70;

    .box {
      display: flex;
      flex-direction: column;
      justify-content: center;
      min-width: 100rem;
      width: auto;
      height: 90rem;
      border-radius: 4px;
      border: 1px solid #d9d9d9;
      padding: 12rem;
      margin-right: 10rem;
      margin-bottom: 20rem;
    }
  }
}

.inlineD {
  display: flex;
  justify-content: space-around;
}

.inlineN {
  display: block;
}

// .ac-card {
//     padding: 20rem;
//     background-color: #e1e1e1;
//   }

.content::-webkit-scrollbar {
  display: none;
}

:deep(.n-spin-container) {
  width: 100%;
  height: 100%;
}

:deep(.n-scrollbar-container) {
  width: 100%;
  height: 100%;
}

:deep(.n-scrollbar-content) {
  width: 100%;
  height: 100%;
}

:deep(.n-spin-content) {
  width: 100%;
  height: 100%;
}
</style>
